package com.labofjet.system.util;

import com.github.pagehelper.PageInfo;
import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.enums.BaseEnum;
import com.labofjet.common.util.SpringUtils;
import com.labofjet.system.dto.SysCommonQueryDto;
import com.labofjet.system.dto.SysDictionaryInfoDto;
import com.labofjet.system.enums.EColumn;
import com.labofjet.system.enums.ETable;
import com.labofjet.system.mapper.SysCommonQueryMapper;
import com.labofjet.system.service.impl.SysDictionaryInfoServiceImpl;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 字典帮助类
 */
public class SysDicUtils {
    /**
     * 获取字典的名称BySn
     *
     * @param e
     * @param sn
     * @return
     */
    public static String getDicInfoTextBySn(BaseEnum e, String sn) {
//		SysCommonQueryMapper mapper = SpringUtils.getApplicationContext().getBean(SysCommonQueryMapper.class);
//        String s = mapper.find(new SysCommonQueryDto.Builder().tableName(ETable.DIC_INFO.getCode())
//                .sn(sn).columnName(EColumn.PSN.getCode()).columnValue("'" + e.getCode() + "'").build())
//                .get(EColumn.TEXT.getCode()).toString();
//        return s;


        SysDictionaryInfoServiceImpl SysDictionaryInfoService = SpringUtils.getApplicationContext().getBean(SysDictionaryInfoServiceImpl.class);
        ContextDto contextDto = new ContextDto();
        Map<String, Object> requestParams = contextDto.getRequestParams();
        requestParams.put("psn", e.getCode());
        requestParams.put("sn", sn);
        PageInfo<SysDictionaryInfoDto> list = SysDictionaryInfoService.list(contextDto);
        if (CollectionUtils.isNotEmpty(list.getList())) {
            return list.getList().get(0).getText();
        }
        return null;
    }

    /**
     * 获取字典的SnBy名称,最好不要用,因为字典值可能会变化,那旧数据的text就和最新的不一致,会导致sn找不到
     *
     * @param e
     * @param text
     * @return
     */
    @Deprecated
    public static String getDicInfoSnByText(BaseEnum e, String text) {
        SysCommonQueryMapper mapper = SpringUtils.getApplicationContext().getBean(SysCommonQueryMapper.class);
        return mapper.find(new SysCommonQueryDto.Builder().tableName(ETable.DIC_INFO.getCode())
                .text(text).columnName(EColumn.PSN.getCode()).columnValue("'" + e.getCode() + "'").build())
                .get(EColumn.TEXT.getCode()).toString();
    }

    /**
     * 常用于分页查询出来数据以后批量设置字典值(因为分页基本只查单表). 比较浅的封装
     *
     * @param src
     * @param handler
     * @param <S>
     */
    public static <S> void combineDicInfo(List<S> src, DicInfoHandler<S> handler) {
        if (CollectionUtils.isEmpty(src)) {
            return;
        }
        for (S s : src) {
            handler.handle(s);
        }
    }

    public interface DicInfoHandler<S> {
        default void handle(S s) {

        }
    }
}
